import u from "@/plugins/Ccom";
export default async function (ctx) {
  // 当前城市数据
  var getCurrentCityData = await u.http({
    url: "/pc/city/queryCityInfo",
    params: {
      host: ctx.req.headers.host,
      ip: ctx.req.headers['x-true-ip'] || '',
    },
  });
  if (getCurrentCityData.code == 200) {
    ctx.getCurrentCityData = getCurrentCityData || {};
    ctx.currentCity = getCurrentCityData.data || {
      id: 510100,
      aliases: 'cd',
      cityName: '成都'
    };
    ctx.cityCode = getCurrentCityData.data.cityCode || ''; // 城市code
    // ctx.prefixUrl = getCurrentCityData.data.prefixUrl || ''; // 完整域名
    ctx.currentCity.prefixUrlMain = getCurrentCityData.data.prefixUrl || '';
    ctx.currentCity.cityNameMain = getCurrentCityData.data.cityName || '';
    ctx.prefixUrl = `http://${ctx.req.headers.host}`; // 完整域名 202203131640 sry
    ctx.currentCity.prefixUrl = `http://${ctx.req.headers.host}`; // 202203131640 sry
    ctx.currentCity.cityName = `http://${ctx.req.headers.host}` == u.mainDomain ? '' : getCurrentCityData.data.cityName; // 202203131640 sry
    ctx.province = getCurrentCityData.data.provinceShortName || '';
    ctx.cityName = `http://${ctx.req.headers.host}` == u.mainDomain ? '' : getCurrentCityData.data.cityName; // 202203131640 sry
  }
  // 追加meta城市指向
  ctx.app.head.meta.push({
    name: 'location',
    content: `province=${ctx.province};city=${ctx.cityName}`
  })
  // 添加适配
  ctx.app.head.meta.push({
    name: 'mobile-agent',
    content: `format=html5; url=http://m.mfgjw.com/${ctx.currentCity.aliases}${ctx.route.fullPath}`
  })
  ctx.app.head.link.push({
    rel: 'alternate',
    media: 'only screen and (max-width:640px)',
    href: `http://m.mfgjw.com/${ctx.currentCity.aliases}${ctx.route.fullPath}`
  })
  // 如果是移动端跳转到手机端网站
  var userAgent = ctx.req.headers['user-agent'];
  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) {
    let path = ctx.req.headers.host.split('.')[0] + ctx.route.fullPath || `/${getCurrentCityData.data.aliases}/`;
    ctx.redirect(`http://m.mfgjw.com/${path}`);
  }
  // // 是否开启短信验证
  // var getSMSData = await u.http({
  //   url: "/app/cfg/queryCfgDataByCmid",
  //   params: {
  //     cmId: 424
  //   }
  // });
  // ctx.smsState = (getSMSData.code == 200) ? Number(getSMSData.data[0].content) : 0;
  // 获取开通城市
  var getCityData = await u.http({
    url: "/app/district/queryCityAllByWeb",
  });
  if (getCityData.code == 200) {
    var cityList = [];
    getCityData.data.forEach((item) => {
      cityList.push({ letter: item.letter });
      let itemArr = [];
      item.cityList.forEach((ite) => {
        itemArr.push(ite);
      });
      cityList.push(itemArr);
    });
    ctx.cityList = cityList || [];
  }
  // 获取友情链接
  var getLinksList = await u.http({
    url: "/pc/link/queryConfigLink",
    params: {
      host: (ctx.req.headers.host == 'www.mfgjw.com' || ctx.req.headers.host == 'mfgjw.com') ? '' : ctx.req.headers.host,
      pageSize: 200
    }
  })
  if (getLinksList.code == 200) {
    ctx.currentCity.linksShow = false
    let linksList = []
    getLinksList.data.list.forEach(item => {
      if (item.pathRoute == 'mfgjw.com' && (ctx.req.headers.host == 'www.mfgjw.com' || ctx.req.headers.host == 'mfgjw.com')) {
        linksList.push(item)
      }
      let pathRoute = ctx.route.path.split('/')[1] || ctx.route.path
      if (item.pathRoute == pathRoute && ctx.req.headers.host != 'www.mfgjw.com' && ctx.req.headers.host != 'mfgjw.com') {
        linksList.push(item)
      }
    })
    ctx.currentCity.linksList = linksList
  }
  var splitQuyuUrl = [] // 拆分区域路径
  var splitJiedaoUrl = [] // 拆分街道路径
  // 设置路径
  function setHref(obj) {
    let nowHref = '' // 新路径
    let nowArr = [] // 新拼接数组
    // 拼接区域路径
    if (!u.empty(obj.aliases) && obj.aliases.charAt(0) == 'c') {
      // 没有区域参数 添加当前区域参数
      let nowSplitQuyuUrl = obj.aliases != 'c0' ? [obj.aliases] : []
      // 数组重新组合
      let nowSplitUrl = nowArr.concat(
        nowSplitQuyuUrl,
      )
      u.emptyArrayIsNull(nowSplitUrl) // 清除空数据
      nowHref = nowSplitUrl.join('-')
    }

    // 拼接街道路径
    if (!u.empty(obj.aliases) && obj.aliases.charAt(0) == 'd') {
      // 替换摘除不需要的组合
      let splitJiedaoUrlStr = splitJiedaoUrl.join('_')
      let nowSplitJiedaoUrlStr = ''
      if (splitJiedaoUrlStr.indexOf(obj.aliases) > -1) {
        // 当前别名参数在页面路径上存在 替换为空
        let splitJiedaoUrlStr1 = splitJiedaoUrlStr.replace(obj.aliases, '')
        splitJiedaoUrlStr1 = splitJiedaoUrlStr1.split('_')
        splitJiedaoUrlStr1 = u.emptyArrayIsNull(splitJiedaoUrlStr1)
        nowSplitJiedaoUrlStr = splitJiedaoUrlStr1.join('_')
      } else {
        // 当前别名参数在页面路径上不存在 末尾追加
        nowSplitJiedaoUrlStr = splitJiedaoUrlStr
          ? `${splitJiedaoUrlStr}_${obj.aliases}`
          : obj.aliases
      }
      // 数组重新组合
      let nowSplitUrl = nowArr.concat(
        splitQuyuUrl,
        nowSplitJiedaoUrlStr,
      )
      u.emptyArrayIsNull(nowSplitUrl) // 清除空数据
      nowHref = nowSplitUrl.join('-')
    }

    return `/lpcx/${nowHref}`
  }
  // 获取区域
  var getRegion = await u.http({
    url: '/app/district/queryDistrictByCityId',
    params: {
      cityId: ctx.cityCode,
    },
  })
  if (getRegion.code == 200) {
    // 添加全部
    getRegion.data.unshift({
      id: '',
      lat: '',
      lng: '',
      name: '全部',
      pinyin: '',
      shortName: '全部',
      streetList: [],
      aliases: 'c0',
    })
    // 循环区域
    getRegion.data.forEach((item) => {
      item.href = setHref(item) // 设置跳转路径
    })
    ctx.regionList = getRegion.data
  }
}